package com.zhuoyue.biz.core.command.impl.intelligence;

import com.zhuoyue.biz.core.api.domain.DeviceAndGatewayDO;
import com.zhuoyue.biz.core.api.domain.Group;
import com.zhuoyue.biz.core.api.dto.req.ControlReq;
import com.zhuoyue.biz.core.command.cmd.common.faa.ColorfulBulbLampTwo0Faa0B03;
import com.zhuoyue.biz.core.command.cmd.common.faa.SilentCurtain0Faa0E02;
import com.zhuoyue.biz.core.command.constant.DuoCaiDeng0Faa0B02CmdDeal;
import com.zhuoyue.biz.core.command.impl.ShuangSeWen0Faa0D02;
import com.zhuoyue.common.constant.ControlType;
import com.zhuoyue.common.utils.CmdUtils;
import com.zhuoyue.common.utils.Time;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author wjming
 * @ClassName: GroupCmd
 * @Description:
 * @Date 2021-07-14 20:20
 */
@Repository
public class GroupCmd {
    @Autowired
    private RedisTemplate redisTemplate;

    private static GroupCmd groupCmdStatic;
    private static final String DEAL_07 = "07";
    private static final int GROUP_CODE_SIZE_33 = 33;
    private static final int GROUP_CODE_SIZE_32 = 32;
    private static final int DEVICE_COUNT_20 = 20;

    @PostConstruct
    public void init() {
        groupCmdStatic = this;
    }

    /**
     * 同一个群组下多设备操作(增加/删除)
     *
     * @param gatewayMac
     * @param deviceMac
     * @param code       设备个数
     * @param deal       01:增加 02::删除
     * @return
     */
    public static String getCommandSet(String gatewayMac, String deviceMac, int deviceCount, String code, String deal, String randomCode) {
        String deviceCountStr = CmdUtils.intToHexTwo(deviceCount);

        String cmd3To12 = "52" + "00" +
                gatewayMac + deal + randomCode + "" + deviceCountStr + deviceMac +
                code + "00";

        String cmd2 = CmdUtils.getDateLength2(cmd3To12);

        String cmd13 = CmdUtils.getCmdBodySum(cmd3To12);

        String fullCmd = DuoCaiDeng0Faa0B02CmdDeal.CloseControl.CMD_1 + cmd2 +
                cmd3To12 +
                cmd13 +
                DuoCaiDeng0Faa0B02CmdDeal.CloseControl.CMD_14;
        return fullCmd;
    }


    /**
     * 一个设备操作多个群组的情况单设备操作(增加/删除)
     * 03:单添加
     * 04:单删除
     */

    public static String oneDeviceDeal(String gatewayMac, String deviceMac, String groupCode, String deal, String randomCode) {
        StringBuilder code = new StringBuilder(groupCode);
        if (DEAL_07.equals(deal)) {
            if (groupCode.length() < GROUP_CODE_SIZE_33) {
                for (int i = code.length(); i < GROUP_CODE_SIZE_32; i++) {
                    code.append("0");
                }
            }
        }


        String cmd3To12 = "52" + "00" +
                gatewayMac + deal + randomCode + deviceMac +
                code.toString();

        String cmd2 = CmdUtils.getDateLength(cmd3To12);

        String cmd13 = CmdUtils.getCmdBodySum(cmd3To12);

        String fullCmd = DuoCaiDeng0Faa0B02CmdDeal.CloseControl.CMD_1 + cmd2 +
                cmd3To12 +
                cmd13 +
                DuoCaiDeng0Faa0B02CmdDeal.CloseControl.CMD_14;
        return fullCmd;
    }


    /**
     * 清空
     * 06
     */
    public static String groupDeviceClear(String gatewayMac, String deviceMac, int deviceCount, int code, String deal) {
        //默认构造方法
        Random random = new Random();
        int i2 = random.nextInt(10000);
        String deviceCountStr = "20";
        if (deviceCount > DEVICE_COUNT_20 && deviceCount < GROUP_CODE_SIZE_32) {
            deviceCountStr = "32";
        }

        String cmd3To12 = "52" + "00" +
                gatewayMac + deal + i2 + "" + deviceCountStr + deviceMac +
                code;

        String cmd2 = CmdUtils.getDateLength2(cmd3To12);

        String cmd13 = CmdUtils.getCmdBodySum(cmd3To12);

        String fullCmd = DuoCaiDeng0Faa0B02CmdDeal.CloseControl.CMD_1 + cmd2 +
                cmd3To12 +
                cmd13 +
                DuoCaiDeng0Faa0B02CmdDeal.CloseControl.CMD_14;
        return fullCmd;
    }

    public static String commandDeal(String type, Map<String, Object> map, String gatewayMac, String code) throws ParseException {
        String cmd = "";
        switch (type) {
            case "light":
                String codeStr = code + "00";
                cmd = ShuangSeWen0Faa0D02.getCommand(map, gatewayMac, codeStr, null, true);
                break;
            case "curtain":
                String curtainCode = code + "00";
                DeviceAndGatewayDO deviceAndGatewayDO = new DeviceAndGatewayDO();
                deviceAndGatewayDO.setGatewayMac(gatewayMac);
                //将群组编号赋值给设备mac
                deviceAndGatewayDO.setZigbeeMac(curtainCode);
                ControlReq controlReq = new ControlReq();
                String controlType = (String) map.get("controlType");
                if (!StringUtils.isEmpty(controlType)) {
                    controlReq.setControlType(controlType);
                }

                cmd = SilentCurtain0Faa0E02.control(deviceAndGatewayDO, controlReq, true);
                break;

            default:
                break;

        }
        return cmd;
    }

    /**
     * @param group
     * @param controlReq
     * @return
     * @throws ParseException
     */
    public static String commandDeal(Group group, ControlReq controlReq) throws ParseException {
        String cmd = "";
        switch (group.getType()) {
            case "curtain":
                String curtainCode = group.getCode() + "00";
                DeviceAndGatewayDO deviceAndGatewayDO = new DeviceAndGatewayDO();
                deviceAndGatewayDO.setGatewayMac(group.getGatewayMac());
                //将群组编号赋值给设备mac
                deviceAndGatewayDO.setZigbeeMac(curtainCode);
                cmd = SilentCurtain0Faa0E02.control(deviceAndGatewayDO, controlReq, true);
                break;
            //rgbw类群组，灯带控制器2.0
            case "rgbw":
                String groupCode = group.getCode() + "00";
                deviceAndGatewayDO = new DeviceAndGatewayDO();
                deviceAndGatewayDO.setGatewayMac(group.getGatewayMac());
                deviceAndGatewayDO.setZigbeeMac(groupCode);
                controlReq.getActions().put("groupId", group.getId());

                String controlType = controlReq.getControlType();

                //设置延时关
                if (ControlType.TIMING_TURN_OFF_REQUEST.equals(controlType)) {
                    int delayTime = Integer.parseInt(controlReq.getActions().get("delayTime").toString());
                    String delayTimeStr = CmdUtils.getHighPositionReplacement(CmdUtils.intToHexFour(delayTime));
                    controlReq.setControlType("TurnOffRequest");
                    String deviceCmd = ColorfulBulbLampTwo0Faa0B03.control(deviceAndGatewayDO, controlReq, true);
                    cmd = groupDelayTimeCmd(deviceAndGatewayDO.getGatewayMac(), group.getCode(), delayTimeStr, deviceCmd);
                    //将关闭的时间戳保存到redis
                    long closeTime = Time.toLongMilli(LocalDateTime.now()) + delayTime * 1000L;
                    groupCmdStatic.redisTemplate.opsForValue().set(group.getId() + "_delayTime", closeTime, delayTime, TimeUnit.SECONDS);
                } else if (ControlType.CANCEL_DELAY_REQUEST.equals(controlType)) {
                    //取消延时
                    cmd = groupCancelDelay(deviceAndGatewayDO.getGatewayMac(), group.getCode());
                    groupCmdStatic.redisTemplate.delete(group.getId() + "_delayTime");
                } else {
                    cmd = ColorfulBulbLampTwo0Faa0B03.control(deviceAndGatewayDO, controlReq, true);
                }
                break;
            default:
                break;
        }
        return cmd;
    }

    /**
     * 群组添加延时
     *
     * @param gatewayMac
     * @param code
     * @param time
     * @param data
     * @return
     */
    private static String groupDelayTimeCmd(String gatewayMac, String code, String time, String data) {
        String randomCode = RandomStringUtils.randomNumeric(4);
        String data1 = "53" + "00" + gatewayMac + "01" + randomCode + code + code + "00" + time + data;
        String cmd2 = CmdUtils.getDateLength(data1);

        String cmd13 = CmdUtils.getCmdBodySum(data1);
        return "2A" + cmd2 + data1 + cmd13 + "23";
    }

    /**
     * 群组删除延时
     *
     * @param gatewayMac
     * @param code
     * @return
     */
    private static String groupCancelDelay(String gatewayMac, String code) {
        String randomCode = RandomStringUtils.randomNumeric(4);
        String data1 = "53" + "00" + gatewayMac + "02" + randomCode + code;
        String cmd2 = CmdUtils.getDateLength(data1);

        String cmd13 = CmdUtils.getCmdBodySum(data1);
        return "2A" + cmd2 + data1 + cmd13 + "23";
    }
}
